﻿using Microsoft.AspNetCore.Server.Kestrel.Https;

namespace Quickly.Certs.AspNetCore
{
    public static class BuilderExtensions
    {
        public static HttpsConnectionAdapterOptions UseServerCertificeSelectorQuickly(
            this HttpsConnectionAdapterOptions httpsOptions, 
            IServerCertificateSelector serverCertificateSelector)
        {
            var fallbackSelector = httpsOptions.ServerCertificateSelector;

            httpsOptions.ServerCertificateSelector = (connectionContext, domainName) =>
            {
                var primaryCert = serverCertificateSelector.Select(connectionContext!, domainName);

                return primaryCert ?? fallbackSelector?.Invoke(connectionContext, domainName);
            };

            return httpsOptions;
        }
    }
}
